package com.jingyi.framework.interceptor.impl;

import com.jingyi.common.annotation.CheckOpenId;
import com.jingyi.common.config.JingYiConfig;
import com.jingyi.common.config.WxAuthConfig;
import com.jingyi.common.core.domain.entity.WxUser;
import com.jingyi.common.exception.user.IllegalOpenIdException;
import com.jingyi.common.utils.StringUtils;
import com.jingyi.system.service.IWxUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Proxy;
import java.util.Objects;

/**
 * @Author: wangzhong
 * @Date: 2023/7/12 18:35
 * @Description:
 **/
@Component
public class CheckOpenIdInterceptor implements HandlerInterceptor {
    @Autowired
    IWxUserService wxUserService;
    @Autowired
    JingYiConfig jingYiConfig;

    @Autowired
    WxAuthConfig wxAuthConfig;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception
    {
        String openId = request.getHeader("Open-Id");
        if (handler instanceof HandlerMethod && jingYiConfig.getCheckOpenId())
        {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            CheckOpenId method = AnnotationUtils.findAnnotation(handlerMethod.getMethod(), CheckOpenId.class);
            if (Objects.nonNull(method))
            {
                if(StringUtils.isEmpty(openId)){
                    throw new IllegalOpenIdException();
                }else{
                    WxUser wxUser = wxUserService.selectUserByOpenId(openId);
                    if(Objects.isNull(wxUser)){
                        throw new IllegalOpenIdException();
                    }
                }
            }
            
            return true;
        }
        else
        {
            return true;
        }
    }
}
